use std::cmp::Ordering;
use whisper_rs_sys::WHISPER_SAMPLE_RATE;

use super::{SegmentTime, PCM_SIZE_ONE_SECOND};

#[derive(Debug, PartialEq)]
pub struct Segment {
    text: String,
    start: SegmentTime,
    end: SegmentTime,
}

impl Segment {
    pub fn offset_size(&self) -> usize {
        (self.end.millis() * (PCM_SIZE_ONE_SECOND as i64 / 1000)) as _
    }
}

impl From<(String, i64, i64)> for Segment {
    fn from((text, start, end): (String, i64, i64)) -> Self {
        assert!(start < end);
        Self {
            text,
            start: start.into(),
            end: end.into(),
        }
    }
}

impl PartialOrd for Segment {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.start >= other.end {
            Some(Ordering::Greater)
        } else if self.end <= other.start {
            Some(Ordering::Less)
        } else {
            unreachable!()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn segment_partial_order_less_should_work() {
        let seg1: Segment = ("1".into(), 1, 2).into();
        let seg2: Segment = ("2".into(), 2, 3).into();
        assert!(seg1 < seg2);
    }

    #[test]
    fn segment_partial_order_greater_should_work() {
        let seg1: Segment = ("1".into(), 1, 2).into();
        let seg2: Segment = ("2".into(), 2, 3).into();
        assert!(seg2 > seg1);
    }

    #[test]
    #[should_panic]
    fn segment_partial_order_should_panic() {
        let seg1: Segment = ("1".into(), 1, 4).into();
        let seg2: Segment = ("2".into(), 2, 3).into();
        assert!(seg2 < seg1);
        assert!(seg2 > seg1);
    }
}
